<template>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="materialCode" label="物料编码" width="150" />
        <el-table-column prop="materialName" label="物料名称" width="120" />
        <el-table-column prop="materialModel" label="物料型号" width="120" />
        <el-table-column prop="unitMaterial" label="物料单位" width="120" />
        <el-table-column prop="quantityMaterialInput" label="投料量" width="120" />
        <el-table-column prop="theoreticalMaterial" label="理论投料比例" width="120" />
        <el-table-column prop="actualMaterial" label="实际投料比例" width="120" />
        <el-table-column prop="materialInputOperator" label="投料人员" width="120" />
        <el-table-column prop="requirementDescription" label="工艺要求说明" width="120" />
        <el-table-column fixed="right" label="Operations" min-width="120">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="dialogFormVisible = true; FanTian(scope.row)">
                    修改
                </el-button>
                <el-button link type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 修改 -->
    <el-dialog v-model="dialogFormVisible" title="修改信息" width="500">
        <el-form :model="form">
            <el-form-item label="物料名称">
                <el-input v-model="form.materialName" @click="dialogTableVisible = true" />
            </el-form-item>
            <el-form-item label="物料编码">
                <el-input v-model="form.materialCode" />
            </el-form-item>
            <el-form-item label="物料型号">
                <el-input v-model="form.materialModel" />
            </el-form-item>
            <el-form-item label="物料单位">
                <el-input v-model="form.unitMaterial" />
            </el-form-item>
            <el-form-item label="投料量">
                <el-input v-model="form.quantityMaterialInput" />
            </el-form-item>
            <el-form-item label="理论投料比例">
                <el-input v-model="form.theoreticalMaterial" />
            </el-form-item>
            <el-form-item label="实际投料比例">
                <el-input v-model="form.actualMaterial" />
            </el-form-item>
            <el-form-item label="投料人员">
                <el-select v-model="form.materialInputOperator" placeholder="请选择投料人员">
                    <el-option v-for="user in getuserlist" :key="user.userId" :label="user.userName"
                        :value="user.userName">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="工艺要求说明">
                <el-input v-model="form.requirementDescription" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">提交</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog v-model="dialogTableVisible" title="物料信息" width="800">
        <el-table :data="queryMateralList" @row-click="handleRowClick">
            <el-table-column property="material_code" label="物料编号" width="150" />
            <el-table-column property="material_name" label="物料名称" width="150" />
            <el-table-column property="specification" label="规格" />
            <el-table-column property="unit" label="单位" width="150" />
        </el-table>
    </el-dialog>
    <el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[1, 3, 5, 7]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
</template>

<script lang="ts" setup>
import axios from 'axios';
import { onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';

const dialogFormVisible = ref(false);
const dialogTableVisible = ref(false);

const getuserlist = ref([{
    userId: 0,
    userName: "",
    password: "",
    userNickName: ""
}])
const getuser = () => {
    axios.get('http://10.223.8.6:8000/read/api/User/GetUse').then((response) => {
        getuserlist.value = response.data.data
        console.log("用户信息", getuserlist.value)
    })
}

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  page.value.pageSize = val
  queryMaterial()
}

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  page.value.pageIndex = val
  queryMaterial()
}

const onSubmit = () => {
    console.log('submit!')
    axios.post(`https://localhost:7229/api/Feeding/UpdateFeeding`, {
        feedingId: form.value.feedingId,
        materialCode: form.value.materialCode,
        materialName: form.value.materialName,
        materialModel: form.value.materialModel,
        unitMaterial: form.value.unitMaterial,
        quantityMaterialInput: form.value.quantityMaterialInput,
        theoreticalMaterial: form.value.theoreticalMaterial,
        actualMaterial: form.value.actualMaterial,
        materialInputOperator: form.value.materialInputOperator,
        requirementDescription: form.value.requirementDescription
    }).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success('提交成功');
        } else {
            ElMessage.error('提交失败');
        }
    })
}

const handleRowClick = (row) => {
    form.value.materialCode = row.material_code;
    form.value.materialName = row.material_name;
    form.value.materialModel = row.specification;
    form.value.unitMaterial = row.unit;
    dialogTableVisible.value = false;
}

const FanTian = (row) => {
    form.value = row;
}

const queryMateralList = ref([{
    materialId: 0,
    material_code: "",
    material_name: "",
    specification: "",
    unit: "",
    storage_quantity: 0
}]);
const queryMaterial = () => {
    axios.get('http://localhost:5118/api/MaterialPreparation/GetMaterial')
        .then(res => {
            queryMateralList.value = res.data.data
            console.log("物料信息",queryMateralList.value)
        })
}

const tableData = ref([{
    feedingId: 0,
    materialCode: "",
    materialName: "",
    materialModel: "",
    unitMaterial: "",
    quantityMaterialInput: "",
    theoreticalMaterial: "",
    actualMaterial: "",
    materialInputOperator: "",
    requirementDescription: ""
}]);

const form = ref({
    feedingId: 0,
    materialCode: "",
    materialName: "",
    materialModel: "",
    unitMaterial: "",
    quantityMaterialInput: "",
    theoreticalMaterial: "",
    actualMaterial: "",
    materialInputOperator: "",
    requirementDescription: ""
})

onMounted(() => {
    getFeeding();
    getuser();
    queryMaterial();
});

const page = ref({
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
    totalPage: 0
});

const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除这条记录吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        // 调用删除接口
        await axios.post(`https://localhost:7229/api/Feeding/Handle`, {
            feedingId: row.feedingId
        }).then((res) => {
            if (res.data.code == 200) {
                ElMessage.success('删除成功');
            } else {
                ElMessage.error('删除失败');
            }
        })

        // 重新获取数据，刷新表格
        await getFeeding();
    } catch (error) {
        if (error === 'cancel') {
            return;
        }
        ElMessage.error('删除失败，请稍后重试');
        console.error('删除失败', error);
    }
};

// 显示方法
const getFeeding = async () => {
    try {
        const res = await axios.get('https://localhost:7238/api/Feeding/Handle', {
            params: {
                pageIndex: page.value.pageIndex,
                pageSize: page.value.pageSize
            }
        });
        tableData.value = res.data.data;
        page.value.totalCount = res.data.totalCount;
        page.value.totalPage = res.data.totalPage;
    } catch (error) {
        ElMessage.error('数据获取失败，请稍后重试');
        console.error('数据获取失败', error);
    }
};
</script>